<template>
  <el-upload
    v-loading="videoLoadingFlag"
    :action="fileUrl"
    class="file-uploader"
    :on-remove="handleRemoveVideo"
    :show-file-list="true"
    multiple
    :limit="5"
    :on-exceed="handleExceed"
    :on-success="onSuccessVideo"
    :before-upload="beforeVideoUpload"
    :file-list="videoPath"
    :disabled="detail"
  >
    <div class="upload-video-panel">
      <el-button class="upload-btn" size="small" type="primary" :disabled="detail">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">上传文件不超过10MB</div>
    </div>
  </el-upload>
</template>

<script>
import { fileUrl, staticImgUrl } from '@/url'

export default {
  name: 'TableUploadVideo',
  components: {
  },
  props: {
    videoList: {
      type: Array,
      default: () => []
    },
    detail: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileUrl, staticImgUrl,
      imagePreview: false,
      videoLoadingFlag: false,
      showVideoPath: [],
      videoPath: []
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      if (this.videoList !== null && this.videoList.length !== 0) {
        this.videoPath = this.videoList
      }
    },
    getPaths() {
      return this.videoPath
    },
    // 视频
    handleRemoveVideo(file, fileList) {
      this.videoPath = []
      fileList.forEach(value => {
        this.videoPath.push({
          name: value.name,
          url: value.url
        })
      })
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    onSuccessVideo(res, file, fileList) {
      if (res.success) {
        this.videoPath.push({
          name: file.name,
          url: file.response.data.url
        })
      } else {
        this.$message.error(res.message)
      }
    },
    beforeVideoUpload(file) {
      var filename = file.name
      var index1 = filename.lastIndexOf('.')
      var index2 = filename.length
      var suffix = filename.substring(index1 + 1, index2)
      if (suffix !== 'mp4') {
        this.$message.error('请上传mp4格式视频')
        return false
      }

      const isLt6M = file.size / 1024 / 1024 < 10
      if (!isLt6M) {
        this.$message.error('上传视频大小不能超过 10MB!')
        this.loadingFlag = false
      }
      return isLt6M
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
